<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="./vue.js"></script>
  <script src="./vuex.js"></script>
</head>

<body>
  <div id="app">
    <custom-button type="decrement"></custom-button>
    {{$store.state.num}}
    <custom-button type="increment"></custom-button>
    <hr>
    {{$store.getters.getCount}}
    <hr>
    <h1>modules</h1>
    {{$store.state.cart.cartno}}
    <br>
    {{
      $store.state.product.name
    }}
  </div>


  <script>

    Vue.component('custom-button', {
      props: ['type'],
      template: `<button @click="handleClick">{{getBtnText}}</button>`,
      computed: {
        getBtnText() {
          if (this.type === "increment") {
            return '+'
          } else {
            return '-';
          }
        }
      },
      methods: {
        handleClick() {
          if (this.type === "increment") {
            //不建议，会丢失时间旅行
            // this.$store.state.num += 1;
            this.$store.commit('crement', 1)
            // this.$store.dispatch('asyncCrement',1)
          } else {
            this.$store.commit('crement', -1)
            // this.$store.dispatch('asyncCrement',-1)
            //不建议，会丢失时间旅行
            // this.$store.state.num -= 1;
          }
        }
      }
    })

    var cart = {
      state: {
        cartno: 3
      }
    }

    var product = {
      namespaced:true,
      state: {
        name: 'apple'
      },
      mutations:{
        updateName(state,val){
          state.name=val;
        }
      }
    }


    var store = new Vuex.Store({
      state: {
        num: 10
      },
      mutations: {
        crement(state, val) {
          state.num += val;
        }
      },
      getters: {
        getCount(state) {
          return state.num * 2;
        }
      },
      actions: {
        asyncCrement({ commit }, val) {
          setTimeout(() => {
            commit('crement', val)
          }, 2000);
        }
      },
      modules: {
        cart,
        product
      }
    })

    var vm = new Vue({
      el: "#app",
      store,
      data: {

      },
      mounted(){
        setTimeout(() => {
          this.$store.commit('product/updateName','orange')
        }, 2000);
      }
    })

  </script>

</body>

</html>